USE [NORTHWND]
GO

/****** Object:  Trigger [dbo].[TR_OrderDetail1]    Script Date: 3/11/2014 7:20:38 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
if (OBJECT_ID ('TR_OrderDetail1') is not null)
	drop trigger [dbo].[TR_OrderDetail1]
go

CREATE TRIGGER [dbo].[TR_OrderDetail1]
	ON [dbo].[Order Details]
	FOR INSERT
AS
	DECLARE @IdP INT
		   ,@Cant INT
		   ,@Stock INT

	SELECT @IdP = I.ProductID, @Cant = I.Quantity
		FROM inserted AS I

	SELECT @Stock = UnitsInStock
			FROM Products
			WHERE ProductID = @IdP 
print @Stock
print @Cant
	IF (@Stock = 0 OR (@Stock - @Cant) <= 0)
		BEGIN

		   RAISERROR('Cantidad insuficiente', 16, 3)

		END
	ELSE
		BEGIN
			
			UPDATE Products SET UnitsInStock = @Stock - @Cant
			WHERE ProductID = @IdP

		END

GO


